/**
 *  Project: CloudstickUtils 
 *  kr.cloudstick.util.crypto-CSAes.java
 * 	
 *	Copyright 2013 Cloudstick (www.cloudstick.kr)
 *
 *	Written by htkim
 *		2013. 3. 27. first written.
 *
 *	Note:	
 */
package kr.cloudstick.util.crypto;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import kr.cloudstick.util.CSException;

public final class CSAes {

	private static final String ALGORITHM = "AES";
	
	private CSAes() {
		throw new AssertionError();
	}
	
	public static byte[] encrypt(final byte[] password, final String plainText)
	{
		try {
			final Key secureKey = new SecretKeySpec(password, ALGORITHM);
			final Cipher cipher = Cipher.getInstance(ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, secureKey);
			return cipher.doFinal(plainText.getBytes("UTF-8"));
		} catch(Exception e) {
			throw new CSException(e);
		}
	}
	
	public static String encryptToBase64(final byte[] password, final String plainText)
	{
		final byte[] encrypted = encrypt(password, plainText);
		return CSCodec.byteToBase64(encrypted);
	}
	
	public static String encryptToBase64(final String passwordBase64, final String plainText)
	{
		final byte[] password = CSCodec.base64ToByte(passwordBase64);
		return encryptToBase64(password, plainText);
	}
	
	public static String decrypt(final byte[] password, final byte[] encrypted)
	{
		try {
			final Key secureKey = new SecretKeySpec(password, ALGORITHM);
			final Cipher cipher = Cipher.getInstance(ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, secureKey);
			final byte[] plainText = cipher.doFinal(encrypted);
			return new String(plainText, "UTF-8");
		} catch(Exception e) {
			throw new CSException(e);
		}
	}
	
	public static String decrypt(final byte[] password, final String encryptedByBase64)
	{
		final byte[] encrypted = CSCodec.base64ToByte(encryptedByBase64);
		return decrypt(password, encrypted);
	}
	
	public static String decrypt(final String passwordBase64, final String encryptedByBase64)
	{
		final byte[] password = CSCodec.base64ToByte(passwordBase64);
		return decrypt(password, encryptedByBase64);
	}
}
